package com.sensePlusVR.fragment;

import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.videolan.libvlc.util.VLCUtil;
import org.xutils.x;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;

import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Process;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.sensePlusVR.adapter.LocalVideoAdapter;
import com.sensePlusVR.application.VRApplication;
import com.sensePlusVR.base.BaseFragment;
import com.sensePlusVR.bean.LocalVideoItem;
import com.sensePlusVR.main.R;
import com.sensePlusVR.media.MediaLibrary;
import com.sensePlusVR.utils.BitmapUtil;
import com.sensePlusVR.utils.MyLog;
import com.sensePlusVR.vlc.misc.MediaDatabase;
import com.sensePlusVR.vlc.misc.MediaWrapper;
import com.sensePlusVR.vlc.misc.VLCInstance;
import com.sensePlusVR.widget.sliddel.ItemRemoveRecyclerView;
import com.sensePlusVR.widget.sliddel.OnItemClickListener;
/**
 * 
 * @author: Loren
 * @create: 2016-8-10下午3:04:04
 * @desc: 本地视频界面
 *
 */
@SuppressLint("HandlerLeak")
@ContentView(R.layout.fragment_video_local)
public class LocalVideoFragment extends BaseFragment implements OnItemClickListener{
	private static final String TAG = LocalVideoFragment.class.getSimpleName();
	private List<LocalVideoItem> videoList;
	private LocalVideoAdapter adapter;
	@ViewInject(R.id.local_video_listview)
	private ItemRemoveRecyclerView local_video_listview;
	
	private MediaLibrary mMediaLibrary;
	private ThumbNailerThread mThumbNailerThread = new ThumbNailerThread();
	private ArrayList<MediaWrapper> mediaList;
	private HashMap<LocalVideoItem, Object> mediaMap = new HashMap<LocalVideoItem, Object>();
	
	private static final int MSG_THUMBNAILER_UPDATE = 1;
	
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
            	//第一次进入加载所有的缩略图，每加载一张更新一次
                case MediaLibrary.MEDIA_ITEMS_UPDATED:
                MyLog.d(TAG, "MEDIA_ITEMS_UPDATED...");	
				getLocalVideo();
                    break;
                    
                case MSG_THUMBNAILER_UPDATE:
                    MediaWrapper media = (MediaWrapper)msg.obj;
                    for(HashMap.Entry<LocalVideoItem, Object> e: mediaMap.entrySet()){
                        if(e.getValue()==media){
                            Bitmap thumbnail = BitmapUtil.getPictureFromCache(media);
                            if(thumbnail != null) {
                            	e.getKey().setBitmap(thumbnail);
                            }
                            break;
                        }
                        adapter.notifyDataSetChanged();
                    }
                	break;
            }
        }
    };
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = x.view().inject(this, inflater, container);
		beforeView();
		initView();
		return view;
	}

	private void beforeView() {
		videoList = new ArrayList<LocalVideoItem>();
		adapter = new LocalVideoAdapter(getActivity(),videoList);
		//adapter.setOnRecyclerViewItemClickListener(this);
	}
	
	private void initView() {
		local_video_listview.setHasFixedSize(true);
		LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
		layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
		local_video_listview.setLayoutManager(layoutManager);
		local_video_listview.setAdapter(adapter);
		local_video_listview.setOnItemClickListener(this);
		
	    mThumbNailerThread.start();
	    mMediaLibrary = MediaLibrary.getInstance();
        if (mMediaLibrary.getMediaItems().isEmpty()) {
            mMediaLibrary.scanMediaItems();
        }
        mMediaLibrary.addUpdateHandler(mHandler);
	    
	    getLocalVideo();
	}

	private void getLocalVideo() {
		mediaList = MediaLibrary.getInstance().getMediaItems();
		MyLog.d(TAG, "mediaList size : " + mediaList.size());
		 //pageIndex = 0;
        //pageMax = (mediaList.size()+MAX_DISP_ITEMS-1)/MAX_DISP_ITEMS;
        loadMedia();
	}
	
	
     class ThumbNailerThread extends  Thread {
        ArrayList<MediaWrapper> mediaList = new ArrayList<MediaWrapper>();
        boolean stopRunning = false;
        Object lock = new Object();

        public void cancel() {
            if(!stopRunning && this.getState() != State.TERMINATED) {
                stopRunning = true;
                interrupt();
            }
        }

        public void addMedia(MediaWrapper media){
            synchronized (lock) {
                mediaList.add(media);
                lock.notify();
            }
        }

        public void clearMedias() {
            synchronized (lock) {
                mediaList.clear();
            }
        }
        
        @Override
        public void run() {
        	Process.setThreadPriority(Process.THREAD_PRIORITY_LOWEST);
            while(!stopRunning){
                synchronized (lock) {
                    if(mediaList.size()==0){
                        try {lock.wait();} catch (Exception e){ MyLog.d(TAG, "wait Exception:"+e);}
                    }
                }
                try {
                    Thread.sleep(3000);
                }catch (Exception e){

                }
                if(stopRunning || isInterrupted()){
                    break;
                }
                MediaWrapper m = null;
                synchronized (lock) {
                    if(mediaList.size()>0) m = mediaList.remove(0);
                }
                if (m!=null && m.getArtworkURL() == null) {  //no need for thumbnail, we have a cover
                    int width = (VRApplication.getAppResources().getDimensionPixelSize(R.dimen.grid_card_thumb_width));
                    int height = (VRApplication.getAppResources().getDimensionPixelSize(R.dimen.grid_card_thumb_height));
                    MyLog.e(TAG, "getThumbnail: "+m.getUri().getPath());

                    //Get bitmap
                    byte[] b = VLCUtil.getThumbnail(VLCInstance.get(), m.getUri(), width, height);
                    Bitmap bmp = null;

                    if (b == null) {// We were not able to create a thumbnail for this item, store a dummy
                        bmp =  Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888);
                        MediaDatabase.setPicture(m, bmp);
                    } else {
                        // Create the bitmap
                        bmp = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
                        Bitmap thumbnail = bmp;

                        thumbnail.copyPixelsFromBuffer(ByteBuffer.wrap(b));

                        MyLog.i(TAG, "Thumbnail created for " + m.getFileName());

                        MediaDatabase.setPicture(m, thumbnail);
                    }
                    mHandler.obtainMessage(MSG_THUMBNAILER_UPDATE, m).sendToTarget();
                }
            }
        }
     }
     
     private void loadMedia(){
         //Bitmap defaultBmp = BitmapFactory.decodeResource(getResources(), R.mipmap.smiley);
   /*      for(JwSubFolder f: folderList){
             f.setVisible(false);
             folderMediaMap.put(f, null);
         }*/
         mThumbNailerThread.clearMedias();
         for(int i=0;i<mediaList.size();i++){
        	 LocalVideoItem item = new LocalVideoItem();
        	 
             //int media_index = i+index*MAX_DISP_ITEMS;
             //if(media_index>=mediaList.size()) break;
             MediaWrapper media = mediaList.get(i);
            // JwSubFolder folder = folderList.get(i);

             /* Thumbnail */
             Bitmap thumbnail = BitmapUtil.getPictureFromCache(media);

             if(thumbnail == null /*defaultBmp*/){
                 mThumbNailerThread.addMedia(media);
                MyLog.e(TAG, "thumbnail == null");
             }
             MyLog.d(TAG, "thumbnail : " + thumbnail);
             String title = media.getTitle() == null?media.getFileName():media.getTitle();
             //String name = null;
             if(!(title.lastIndexOf(".") < 0)){
            	 title = title.substring(0,title.lastIndexOf("."));
             }
             item.setTitle(title);
             item.setBitmap(thumbnail);
             mediaMap.put(item, media);
             videoList.add(item);
             adapter.notifyDataSetChanged();
             //folder.setVisible(true);
        /*     if(pageMax > 1){
                 mJwSubDir.setPageNumber((pageIndex+1)+"",pageMax+"");
             }else{
                 mJwSubDir.setPageNumber("","");
             }*/
         }
         
        // updateOneFrame();
         //defaultBmp.recycle();
     }
     
/*	@Override
	public void OnItemClick(View view, LocalVideoItem item) {
		MyPageJump.pageJumpAddObject(getActivity(), VideoPlayActivity.class, Constant.INTENT_VIDEO_PLAY, item);
	}*/
	
    
	@Override
	public void onPause() {
		super.onPause();
		
	}
	
	@Override
	public void onStop() {
		super.onStop();
		
	}
	
	@Override
	public void onDestroyView() {
		super.onDestroyView();
		
	}
	
	@Override
	public void onDestroy() {
		 mHandler.removeMessages(MSG_THUMBNAILER_UPDATE);
		 mThumbNailerThread.cancel();
		 mMediaLibrary.removeUpdateHandler(mHandler);
		 //mMediaLibrary.removeUpdateHandler(mHandler);
		 super.onDestroy();
	}

	@Override
	public void onItemClick(View view, int position) {
		//MyToast.showMessage(getActivity(), "item title : " + videoList.get(position).getTitle());
		MyLog.d(TAG, "item title : " + videoList.get(position).getTitle());
	}

	@Override
	public void onDeleteClick(int position) {
		adapter.removeItem(position);
	}

	@Override
	public void onTopClick(int position) {
		
	}

	@Override
	public void onDeleteState(int x,int y) {
		
	}

	@Override
	public void recoveryDrawer() {
		// TODO Auto-generated method stub
		
	}
}
